/**
 * 天空盒面板事件处理器
 * 负责所有UI事件的绑定和处理
 */

import * as THREE from '../../lib/three/build/three.module.js';

export class SkyboxPanelEvents {
    constructor(panel, skyboxManager) {
        this.panel = panel;
        this.skyboxManager = skyboxManager;
    }
    
    /**
     * 绑定所有事件
     */
    bindAll() {
        this.bindPresetButtons();
        this.bindModeSwitch();
        this.bindPositionSliders();
        this.bindColorPickers();
        this.bindRotateTextureControls();
        this.bindFlowMapControls();
        this.bindTextureSelectButtons();
        this.bindActionButtons();
    }
    
    /**
     * 绑定预设按钮
     */
    bindPresetButtons() {
        const presetButtons = this.panel.querySelectorAll('.skybox-preset-btn');
        presetButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const presetName = e.target.dataset.preset;
                const event = new CustomEvent('applyPreset', { detail: presetName });
                this.panel.dispatchEvent(event);
            });
        });
    }
    
    /**
     * 绑定模式切换
     */
    bindModeSwitch() {
        const useGradientInput = this.panel.querySelector('#use-gradient');
        useGradientInput.addEventListener('change', (e) => {
            this.skyboxManager.updateParams({ useGradient: e.target.checked });
            this.updateGradientSectionVisibility(e.target.checked);
        });
    }
    
    /**
     * 绑定位置滑块
     */
    bindPositionSliders() {
        this.bindSlider('top-line', 'topLine');
        this.bindSlider('skyline', 'skyline');
        this.bindSlider('ground-line', 'groundLine');
        this.bindSlider('bottom-line', 'bottomLine');
    }
    
    /**
     * 绑定颜色选择器
     */
    bindColorPickers() {
        this.bindColorWithIntensity('top-color', 'top-intensity', 'topColor', 'topColorIntensity');
        this.bindColorWithIntensity('middle-sky-color', 'middle-sky-intensity', 'middleSkyColor', 'middleSkyColorIntensity');
        this.bindColorWithIntensity('skyline-color', 'skyline-intensity', 'skylineColor', 'skylineColorIntensity');
        this.bindColorWithIntensity('ground-color', 'ground-intensity', 'groundColor', 'groundColorIntensity');
        this.bindColorWithIntensity('bottom-color', 'bottom-intensity', 'bottomColor', 'bottomColorIntensity');
    }
    
    /**
     * 绑定旋转贴图控制
     */
    bindRotateTextureControls() {
        this.bindSlider('rotate-tex-hdr', 'rotateTexHdr');
        this.bindSlider('rotate-intensity', 'rotateIntensity');
        this.bindSlider('height-offset', 'heightOffset');
        this.bindSlider('height-scale', 'heightScale');
        this.bindSlider('rotate-speed', 'rotateSpeed');
        this.bindSlider('mask-rotate-speed', 'maskRotateSpeed');
    }
    
    /**
     * 绑定FlowMap控制
     */
    bindFlowMapControls() {
        const useFlowmapInput = this.panel.querySelector('#use-flowmap');
        useFlowmapInput.addEventListener('change', (e) => {
            this.skyboxManager.updateParams({ useFlowMap: e.target.checked });
        });
        
        this.bindSlider('flow-speed', 'flowSpeed');
        this.bindSlider('flow-strength', 'flowStrength');
    }
    
    /**
     * 绑定贴图选择按钮
     */
    bindTextureSelectButtons() {
        // 选择贴图按钮
        const selectButtons = this.panel.querySelectorAll('.skybox-select-texture-btn');
        selectButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const textureType = e.target.dataset.textureType;
                this.selectTexture(textureType);
            });
        });
        
        // 清除贴图按钮
        const clearButtons = this.panel.querySelectorAll('.skybox-clear-texture-btn');
        clearButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const textureType = e.target.dataset.textureType;
                this.clearTexture(textureType);
            });
        });
    }
    
    /**
     * 绑定操作按钮
     */
    bindActionButtons() {
        this.panel.querySelector('#reset-skybox').addEventListener('click', () => {
            const event = new CustomEvent('reset');
            this.panel.dispatchEvent(event);
        });
    }
    
    /**
     * 绑定滑块
     */
    bindSlider(elementId, paramName) {
        const input = this.panel.querySelector(`#${elementId}`);
        const valueSpan = input.nextElementSibling;
        
        input.addEventListener('input', (e) => {
            const value = parseFloat(e.target.value);
            valueSpan.textContent = value.toFixed(2);
            this.skyboxManager.updateParams({ [paramName]: value });
        });
    }
    
    /**
     * 绑定颜色和强度
     */
    bindColorWithIntensity(colorId, intensityId, colorParam, intensityParam) {
        const colorInput = this.panel.querySelector(`#${colorId}`);
        const intensityInput = this.panel.querySelector(`#${intensityId}`);
        
        colorInput.addEventListener('input', (e) => {
            const color = new THREE.Color(e.target.value);
            this.skyboxManager.updateParams({ [colorParam]: color });
        });
        
        intensityInput.addEventListener('input', (e) => {
            const intensity = parseFloat(e.target.value);
            this.skyboxManager.updateParams({ [intensityParam]: intensity });
        });
    }
    
    /**
     * 选择贴图（打开对话框）
     */
    async selectTexture(textureType) {
        try {
            const projectId = window.currentProjectId || window.APP_CONFIG?.currentProjectId;
            if (!projectId) {
                console.error('❌ 未找到项目id');
                return;
            }
            
            // 调用天空盒贴图选择器（复用材质面板的对话框）
            const texture = await this.showTextureSelectDialog(projectId, textureType);
            if (texture) {
                await this.applyTexture(textureType, texture);
            }
        } catch (error) {
            console.error('❌ 选择贴图失败:', error);
        }
    }
    
    /**
     * 清除贴图
     */
    clearTexture(textureType) {
        // 清除输入框显示
        const inputId = this.getTextureInputId(textureType);
        const input = this.panel.querySelector(`#${inputId}`);
        if (input) {
            input.value = '';
        }
        
        // 清除天空盒贴图
        if (textureType === 'rotateTex') {
            this.skyboxManager.material.uniforms.rotateTex.value = null;
            this.skyboxManager.material.uniforms.hasRotateTex.value = false;
        } else if (textureType === 'rotateMaskTex') {
            this.skyboxManager.material.uniforms.rotateMaskTex.value = null;
            this.skyboxManager.material.uniforms.hasRotateMaskTex.value = false;
        } else if (textureType === 'maskFlowMap') {
            this.skyboxManager.material.uniforms.maskFlowMap.value = null;
            this.skyboxManager.material.uniforms.hasMaskFlowMap.value = false;
        }
        
        this.skyboxManager.material.needsUpdate = true;
        console.log(`✅ 已清除贴图: ${textureType}`);
    }
    
    /**
     * 获取贴图输入框ID
     */
    getTextureInputId(textureType) {
        const mapping = {
            'rotateTex': 'rotate-tex-name',
            'rotateMaskTex': 'rotate-mask-name',
            'maskFlowMap': 'flowmap-name'
        };
        return mapping[textureType] || '';
    }
    
    /**
     * 更新渐变色区域显示
     */
    updateGradientSectionVisibility(visible) {
        const sections = this.panel.querySelectorAll('.gradient-section');
        sections.forEach(section => {
            section.style.display = visible ? 'block' : 'none';
        });
    }
    
    /**
     * 更新滑块值
     */
    updateSlider(elementId, value) {
        const input = this.panel.querySelector(`#${elementId}`);
        const valueSpan = input.nextElementSibling;
        
        input.value = value;
        valueSpan.textContent = value.toFixed(2);
    }
    
    /**
     * 更新UI从配置
     */
    updateUIFromConfig(config) {
        if (config.useGradient !== undefined) {
            this.panel.querySelector('#use-gradient').checked = config.useGradient;
            this.updateGradientSectionVisibility(config.useGradient);
        }
        
        // 位置
        if (config.topLine !== undefined) this.updateSlider('top-line', config.topLine);
        if (config.skyline !== undefined) this.updateSlider('skyline', config.skyline);
        if (config.groundLine !== undefined) this.updateSlider('ground-line', config.groundLine);
        if (config.bottomLine !== undefined) this.updateSlider('bottom-line', config.bottomLine);
        
        // 颜色
        if (config.topColor !== undefined) this.panel.querySelector('#top-color').value = config.topColor;
        if (config.middleSkyColor !== undefined) this.panel.querySelector('#middle-sky-color').value = config.middleSkyColor;
        if (config.skylineColor !== undefined) this.panel.querySelector('#skyline-color').value = config.skylineColor;
        if (config.groundColor !== undefined) this.panel.querySelector('#ground-color').value = config.groundColor;
        if (config.bottomColor !== undefined) this.panel.querySelector('#bottom-color').value = config.bottomColor;
        
        // 强度
        if (config.topColorIntensity !== undefined) this.panel.querySelector('#top-intensity').value = config.topColorIntensity;
        if (config.middleSkyColorIntensity !== undefined) this.panel.querySelector('#middle-sky-intensity').value = config.middleSkyColorIntensity;
        if (config.skylineColorIntensity !== undefined) this.panel.querySelector('#skyline-intensity').value = config.skylineColorIntensity;
        if (config.groundColorIntensity !== undefined) this.panel.querySelector('#ground-intensity').value = config.groundColorIntensity;
        if (config.bottomColorIntensity !== undefined) this.panel.querySelector('#bottom-intensity').value = config.bottomColorIntensity;
        
        // 旋转贴图
        if (config.rotateTexHdr !== undefined) this.updateSlider('rotate-tex-hdr', config.rotateTexHdr);
        if (config.rotateIntensity !== undefined) this.updateSlider('rotate-intensity', config.rotateIntensity);
        if (config.heightOffset !== undefined) this.updateSlider('height-offset', config.heightOffset);
        if (config.heightScale !== undefined) this.updateSlider('height-scale', config.heightScale);
        if (config.rotateSpeed !== undefined) this.updateSlider('rotate-speed', config.rotateSpeed);
        if (config.maskRotateSpeed !== undefined) this.updateSlider('mask-rotate-speed', config.maskRotateSpeed);
        
        // FlowMap
        if (config.useFlowMap !== undefined) this.panel.querySelector('#use-flowmap').checked = config.useFlowMap;
        if (config.flowSpeed !== undefined) this.updateSlider('flow-speed', config.flowSpeed);
        if (config.flowStrength !== undefined) this.updateSlider('flow-strength', config.flowStrength);
    }
    
    /**
     * 显示贴图选择对话框（复用材质面板的对话框）
     */
    async showTextureSelectDialog(projectId, textureType) {
        try {
            // 加载项目中的所有贴图
            const textures = await this.loadProjectTextures(projectId);
            
            // 创建对话框
            const dialog = document.createElement('div');
            dialog.className = 'texture-select-dialog';
            
            dialog.innerHTML = `
                <div class="texture-select-dialog-content">
                    <div class="texture-select-dialog-header">
                        <h3>🖼️ 选择贴图</h3>
                        <button class="close-btn">✕</button>
                    </div>
                    <div class="texture-select-dialog-search">
                        <input type="text" placeholder="搜索贴图..." id="texture-search-input">
                    </div>
                    <div class="texture-select-dialog-body" id="texture-select-body">
                        ${textures.length === 0 ? this.renderEmptyTextureState() : this.renderTextureGrid(textures, projectId)}
                    </div>
                    <div class="texture-select-dialog-footer">
                        <div class="texture-select-dialog-footer-right">
                            <button class="texture-select-cancel-btn" id="btn-cancel-select">取消</button>
                            <button class="texture-select-confirm-btn" id="btn-confirm-select" disabled>确定</button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(dialog);
            
            let selectedTexture = null;
            
            // 搜索功能
            const searchInput = dialog.querySelector('#texture-search-input');
            searchInput.addEventListener('input', (e) => {
                const keyword = e.target.value.toLowerCase();
                const filteredTextures = textures.filter(tex => 
                    (tex.displayName || tex.name || '').toLowerCase().includes(keyword)
                );
                
                const body = dialog.querySelector('#texture-select-body');
                body.innerHTML = filteredTextures.length === 0 
                    ? this.renderEmptyTextureState('未找到匹配的贴图') 
                    : this.renderTextureGrid(filteredTextures, projectId);
                
                // 重新绑定点击事件
                this.bindTextureItemClickEvents(dialog, (texture) => {
                    selectedTexture = texture;
                    dialog.querySelector('#btn-confirm-select').disabled = false;
                });
            });
            
            // 绑定贴图项点击事件
            this.bindTextureItemClickEvents(dialog, (texture) => {
                selectedTexture = texture;
                dialog.querySelector('#btn-confirm-select').disabled = false;
            });
            
            // 返回Promise
            return new Promise((resolve) => {
                const closeDialog = () => {
                    dialog.remove();
                    document.removeEventListener('keydown', handleEsc);
                };
                
                // 取消按钮
                dialog.querySelector('#btn-cancel-select').addEventListener('click', () => {
                    closeDialog();
                    resolve(null);
                });
                
                // 确定按钮
                dialog.querySelector('#btn-confirm-select').addEventListener('click', () => {
                    closeDialog();
                    resolve(selectedTexture);
                });
                
                // 关闭按钮
                dialog.querySelector('.close-btn').addEventListener('click', () => {
                    closeDialog();
                    resolve(null);
                });
                
                // 点击背景关闭
                dialog.addEventListener('click', (e) => {
                    if (e.target === dialog) {
                        closeDialog();
                        resolve(null);
                    }
                });
                
                // ESC键关闭
                const handleEsc = (e) => {
                    if (e.key === 'Escape') {
                        closeDialog();
                        resolve(null);
                    }
                };
                document.addEventListener('keydown', handleEsc);
            });
        } catch (error) {
            console.error('❌ 打开贴图选择对话框失败:', error);
            return null;
        }
    }
    
    /**
     * 加载项目中的所有贴图
     */
    async loadProjectTextures(projectId) {
        try {
            const response = await fetch(`/api/projects/${projectId}/textures`);
            const result = await response.json();
            
            if (result.success) {
                return result.data || [];
            } else {
                throw new Error(result.error || '加载失败');
            }
        } catch (error) {
            console.error('❌ 加载项目贴图失败:', error);
            return [];
        }
    }
    
    /**
     * 渲染贴图网格
     */
    renderTextureGrid(textures, projectId) {
        if (textures.length === 0) {
            return this.renderEmptyTextureState();
        }
        
        const backendUrl = window.APP_CONFIG?.backendUrl || window.location.origin;
        
        const items = textures.map(texture => {
            const size = this.formatFileSize(texture.size);
            const displayName = texture.displayName || texture.name || '未命名';
            const textureUrl = `${backendUrl}/api/projects/${projectId}/textures/${texture.id}/file`;
            
            return `
                <div class="texture-select-item" data-texture-id="${texture.id}">
                    <div class="texture-select-item-preview">
                        <img src="${textureUrl}" alt="${displayName}" loading="lazy">
                    </div>
                    <div class="texture-select-item-info">
                        <div class="texture-select-item-name" title="${displayName}">${displayName}</div>
                        <div class="texture-select-item-size">${size}</div>
                    </div>
                    <div class="texture-select-item-badge">✓</div>
                </div>
            `;
        }).join('');
        
        return `<div class="texture-select-grid">${items}</div>`;
    }
    
    /**
     * 渲染空状态
     */
    renderEmptyTextureState(message = '暂无贴图') {
        return `
            <div class="texture-select-empty">
                <div class="texture-select-empty-icon">🖼️</div>
                <div class="texture-select-empty-text">${message}</div>
            </div>
        `;
    }
    
    /**
     * 绑定贴图项点击事件
     */
    bindTextureItemClickEvents(dialog, onSelect) {
        const items = dialog.querySelectorAll('.texture-select-item');
        const allTextures = [];
        
        items.forEach(item => {
            const textureId = item.dataset.textureId;
            const img = item.querySelector('img');
            const name = item.querySelector('.texture-select-item-name').textContent;
            
            allTextures.push({
                id: textureId,
                url: img.src,
                displayName: name,
                element: item
            });
        });
        
        items.forEach((item, index) => {
            item.addEventListener('click', () => {
                items.forEach(i => i.classList.remove('selected'));
                item.classList.add('selected');
                if (onSelect) {
                    onSelect(allTextures[index]);
                }
            });
        });
    }
    
    /**
     * 格式化文件大小
     */
    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    }
    
    /**
     * 应用选中的贴图
     */
    async applyTexture(textureType, texture) {
        try {
            // 更新输入框显示
            const inputId = this.getTextureInputId(textureType);
            const input = this.panel.querySelector(`#${inputId}`);
            if (input) {
                input.value = texture.displayName || texture.name;
            }
            
            // 加载贴图并应用到天空盒
            const textureUrl = texture.url;
            
            if (textureType === 'rotateTex') {
                await this.skyboxManager.loadRotateTexture(textureUrl);
                console.log('✅ 旋转贴图应用成功');
            } else if (textureType === 'rotateMaskTex') {
                await this.skyboxManager.loadRotateMaskTexture(textureUrl);
                console.log('✅ 旋转遮罩应用成功');
            } else if (textureType === 'maskFlowMap') {
                await this.skyboxManager.loadFlowMapTexture(textureUrl);
                console.log('✅ FlowMap应用成功');
            }
        } catch (error) {
            console.error('❌ 应用贴图失败:', error);
        }
    }
}
